package com.erp.erp_ui.email;

import com.erp.erp_entitys.Email.*;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Email.EmailService;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.Ftp.imp.ImpFtpService;
import com.sun.mail.imap.IMAPFolder;
import com.sun.management.OperatingSystemMXBean;
import org.apache.commons.mail.util.MimeMessageParser;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.DataSource;
import javax.imageio.ImageIO;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.ParseException;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailUnit {
    /**
     * 获取邮箱连接Store对象  有用
     */
    public static Store getStore(email_Pop3 pop3) throws MessagingException {
        String port = pop3.getPop3_port();
        String imapServer = pop3.getPop3_server();
        String protocol = pop3.getPop3_class();
        String username = pop3.getEmail_name();
        String password = pop3.getEmail_code(); // QQ邮箱的授权码
        //有些参数可能不需要
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";//ssl加密,jdk1.8无法使用
        Properties props = new Properties();
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.transport.protocol", protocol); // 使用的协议
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.socketFactory.port", port);
        props.setProperty("mail.imap.partialfetch", "false");
        props.setProperty("mail.imaps.partialfetch", "false");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);

        // 获取Store对象
        Store store = session.getStore(protocol);
        store.connect(imapServer, username, password); // 登陆认证
        return store;
    }

    //设置当前时间的格式  有用
    public static String getNowSqlDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        return date;
    }

    //设置sqlDate格式  有用
    public static String getSqlDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1 = sdf.format(date);
        return date1;
    }

    //设置收取的时间条件  0：默认三个月；1:6个月；2:9个月；3：全部   有用
    public static Date saveDate(int pop_getTime) {
        int i = -3;
        if (pop_getTime == 1) {
            i = -6;
        } else if (pop_getTime == 2) {
            i = -9;
        }
        Date dNowdate = new Date(); //当前时间bai
        Date dBeforedate = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历du
        calendar.setTime(dNowdate);//把当前时间赋给日历
        calendar.add(calendar.MONTH, i); //设置为前3月
        dBeforedate = calendar.getTime(); //得到前3月的时间
        return dBeforedate;
    }

    //获取正文图片cid及图片名  有用
    public static Map<String, String> getContent(MimeMessage m) throws Exception {
        Map<String, String> pictures = new HashMap<>();
        MimeMessageParser parser = new MimeMessageParser(m).parse();
        String contentStr = parser.getHtmlContent();//获取到html文本
        if (contentStr == null) {
            contentStr = parser.getPlainContent();//正文为纯文本
            if (contentStr == null) {
                contentStr = "";
            }
        }
        //获取到cid及图片名
        Set<String> cids = (Set<String>) parser.getContentIds();
        Iterator<String> it = cids.iterator();
        while (it.hasNext()) {
            String cid = it.next();
            // contentStr判断是否含有cid,如果含有需要处理，如果不包含，不需要处理
            if (contentStr.contains(cid)) {
                DataSource ds = parser.findAttachmentByCid(cid);//获取到附件
                if (ds != null) {
                    String dsName = ds.getName();
                    if (dsName == null) {
                        dsName = getRandomFileName();
                    }
                    pictures.put(cid, dsName);
                }
            }
        }
        return pictures;
    }

    //获取一个随机的文件名 有用
    public static String getRandomFileName() {

        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        Random random = new Random();

        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数

        return str + rannum;// 当前时间
    }


    //判断是否包含附件，包含则进行保存  有用
    public static List<String> getAdjunct(MimeMessage m) throws IOException, MessagingException {
        boolean isContainerAttachment = isContainAttachment(m);
        System.out.println("是否包含附件：" + isContainerAttachment);
        List<String> strings = new ArrayList<String>();
        if (isContainerAttachment) {
            saveAttachment(m, strings);//保存附件
        }
        return strings;
    }

    /**
     * 判断邮件中是否包含附件
     *
     * @return 邮件中存在附件返回true，不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
           if(part!=null){
           if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }
                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }
                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part) part.getContent());
        }}
        return flag;
    }

    /**
     * 保存附件
     * 有用
     *
     * @param part 邮件中多个组合体中的其中一个组合体
     * @return
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, List<String> adjuncts) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        //将正文图片及附件名字返回
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    String name = bodyPart.getFileName();//目标管理卡-化妆 品事业部-2组-S tan 20200603.xlsx
                    if (name == null) {
                        name = getRandomFileName();
                    }
                    String filename = "";
                    if (!name.endsWith("?=") && name.indexOf("=?") == -1) {
                        filename = MimeUtility.decodeText(name);
                        filename = getFileName1(filename);
                    } else {
                        filename = MimeUtility.decodeWord(getFileName2(name));
                    }
                    adjuncts.add(filename);
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, adjuncts);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        String name = bodyPart.getFileName();
                        if (name == null) {
                            name = getRandomFileName();
                        }
                        String filename = "";
                        if (!name.endsWith("?=") && name.indexOf("=?") == -1) {
                            filename = MimeUtility.decodeText(name);
                            filename = getFileName1(filename);
                        } else {
                            filename = MimeUtility.decodeWord(getFileName2(name));
                        }
                        adjuncts.add(filename);
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), adjuncts);
        }
    }

    //邮件信息存入数据库  有用
    public static email_email saveEmail(MimeMessage message, String uid, String pop3_server, String sqlDate, email_Pop3 pop3, EmailService emailService, String email_address, UserEntity user) throws Exception {
        //获取已读未读状态
        boolean contains = message.getFlags().contains(Flags.Flag.SEEN);
        int containStatue = 0;
        if (contains == false) {
            containStatue = 1;
        }
        String nowSqlDate = EmailUnit.getNowSqlDate();//获取当前系统时间
        //存储附件
        List<String> adjuncts = getAdjunct(message);//按顺序存附件名称（正文图片--附件）
        //获取正文带图的cid和图片名 key为cid value为图片名
        Map<String, String> pictures = getContent(message);
        String subject = "";
        String subject1 = MimeUtility.decodeText(message.getHeader("subject")[0]);
        if (subject1.endsWith("?=") || subject1.startsWith("=?")) {
            subject = message.getSubject();
        } else {
            subject = subject1;
        }
        String reply = message.getReplyTo()[0].toString();
        try {
            reply = reply.substring(reply.indexOf("<") + 1, reply.indexOf(">"));
        } catch (Exception ex) {

        }
        Address[] recipients = message.getAllRecipients();
        String recipientAddress=reply+";";
        for(Address a : recipients){
            String s=a.toString();
            String[] split = s.split("<");
            String s1 = split[split.length - 1].substring(0, split[split.length - 1].length() - 1);
            if(s1.equals(pop3.getEmail_adress())!=true){
                recipientAddress+=s1+";";
            }

        }
        Integer email_class=2;
        email_deploy deploy = emailService.selectDeploy(user.getCode());
        String blackEmail = deploy.getBlackEmail();
        String blackSubject = deploy.getBlackSubject();
        if(blackEmail!=null){
            String[] split = blackEmail.split("&&");
            for(String s:split){
                if(s.equals(reply)){
                    email_class=6;
                }
            }
        }
        if(blackSubject!=null){
            String[] split = blackSubject.split("&&");
            for(String s:split){
                if(subject.contains(s)){
                    email_class=6;
                }
            }
        }

        email_email email = new email_email(Integer.parseInt(uid), pop3_server, -1, -1, -1, -1, email_class, subject,
                null, reply, null, recipientAddress, null, null, null, message.getSize(), null, sqlDate, null,
                nowSqlDate, message.getContentType(), -1, pop3.getPop3_id(), containStatue, pictures.size(), (adjuncts.size() - pictures.size()), 0, null, 0);
        emailService.addEmail_email(email);
        //如果存在收信规则，按收信规则归并
        List<EmailRules> rules = emailService.selectEmailRulesBycode(user.getCode());
        if(rules.size()>0){
            for(EmailRules rule:rules){
                String rule_context = rule.getRule_context();//对发件人进行归并，地址以，进行分割
                Integer box_id = rule.getBox_id();//归并到该箱子
                String[] split = rule_context.split(",");
                for(String add:split){
                    if(add.equals(reply)){//发件地址和收信规则成功匹配
                        email.setEmail_class(8);
                        List<email_email> emails=new ArrayList<>();
                        emails.add(email);
                        emailService.insertBox_Email(new email_box_emailid(box_id,emails));
                        emailService.updateEmailClass(new changeEmailClass(8,emails));
                        break;
                    }
                }
            }
        }

        //附件、图片、正文信息存入数据库 先存储正文图片信息
        Set<Map.Entry<String, String>> entries = pictures.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            email_adjunct adjunct = new email_adjunct();
            adjunct.setEmail_id(email.getEmail_id());
            adjunct.setIsHasAtta(1);
            adjunct.setOldHasAtta(next.getValue());
            adjunct.setCidHas(next.getKey());
            adjunct.setStatue(0);
            emailService.insertEmail_adjunct(adjunct);
        }
        for (String adjun : adjuncts) {
            if (pictures.containsValue(adjun) == false) {
                email_adjunct adjunct = new email_adjunct();
                adjunct.setEmail_id(email.getEmail_id());
                adjunct.setIsAdunct(1);
                adjunct.setAdjunctName(adjun);
                adjunct.setStatue(0);
                emailService.insertEmail_adjunct(adjunct);
            }
        }
        if (containStatue == 1) {
            message.setFlag(Flags.Flag.SEEN, false);//设置为未读
        }
        return email;
    }

    //文件名处理，清楚换行符
    public static String getFileName1(String name) {
        String file = name.replaceAll(System.getProperty("line.separator"), "");
        Pattern p = Pattern.compile("\\s*|\t|\r|\n|\f|");
        file = p.matcher(file).replaceAll("");
        return file;
    }

    //文件名处理
    public static String getFileName2(String name) throws UnsupportedEncodingException, ParseException {
        String file = getFileName1(name);
        int index = -2;
        for (int i = 0; i < 3; i++) {
            index = file.indexOf("?", index + 1);
        }
        String suff = file.substring(0, index + 1);
        String sub = "\\\\" + suff;
        sub = sub.substring(1, sub.length());
        sub = sub.replace("?", "\\?");
        Pattern pattern = Pattern.compile("\\?\\=");
        Pattern pattern1 = Pattern.compile(sub);
        String s2 = pattern1.matcher(file).replaceAll("");
        String s1 = pattern.matcher(s2).replaceAll("");
        s1 = suff + s1 + "?=";
        return s1;
    }

    //判断附件是否有用，有用则进行保存  有用
    public static void upAdjunct(MimeMessage m, String pathName, List<email_adjunct> adjuncts) throws IOException, MessagingException {
        boolean isContainerAttachment = isContainAttachment(m);
        System.out.println("是否包含附件：" + isContainerAttachment);
        if (isContainerAttachment) {
            upAttachment(m, pathName, adjuncts);//保存附件
        }
    }

    /**
     * 保存附件
     * 有用
     *
     * @param part 邮件中多个组合体中的其中一个组合体
     * @return
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void upAttachment(Part part, String pathName, List<email_adjunct> adjuncts) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    //获取到流
                    BufferedInputStream inputStream = new BufferedInputStream(bodyPart.getInputStream());
                    String name = bodyPart.getFileName();
                    if (name == null) {
                        name = getRandomFileName();
                    }
                    String filename = "";
                    if (!name.endsWith("?=") && name.indexOf("=?") == -1) {
                        filename = MimeUtility.decodeText(name);
                        filename = getFileName1(filename);
                    } else {
                        filename = MimeUtility.decodeWord(getFileName2(name));
                    }
                    String fileRandowName=getRandomFileName();
                    IFtpService ftp = new ImpFtpService();
                    String upPath = ftp.uploadEmailAdjunct(pathName,fileRandowName, inputStream);
                    for (email_adjunct ad : adjuncts) {
                        if (ad.getAdjunctName() != null) {
                            if (ad.getAdjunctName().equals(filename)) {
                                ad.setAdjunctAddress(upPath);
                            }
                        }
                        if (ad.getOldHasAtta() != null) {
                            if (ad.getOldHasAtta().equals(filename)) {
                                ad.setNewHasAtta(upPath);
                            }
                        }
                    }
                } else if (bodyPart.isMimeType("multipart/*")) {
                    upAttachment(bodyPart, pathName, adjuncts);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        BufferedInputStream inputStream = new BufferedInputStream(bodyPart.getInputStream());
                        String name = bodyPart.getFileName();
                        if (name == null) {
                            name = getRandomFileName();
                        }
                        String filename = "";
                        if (!name.endsWith("?=") && name.indexOf("=?") == -1) {
                            filename = MimeUtility.decodeText(name);
                            filename = getFileName1(filename);
                        } else {
                            filename = MimeUtility.decodeWord(getFileName2(name));
                        }
//                        String filename=getRandomFileName();
                        IFtpService ftp = new ImpFtpService();
                        String upPath = ftp.uploadEmailAdjunct(pathName, filename, inputStream);
                        for (email_adjunct ad : adjuncts) {
                            if (ad.getAdjunctName() != null) {
                                if (ad.getAdjunctName().equals(filename)) {
                                    ad.setAdjunctAddress(upPath);
                                }
                            }
                            if (ad.getOldHasAtta() != null) {
                                if (ad.getOldHasAtta().equals(filename)) {
                                    ad.setNewHasAtta(upPath);
                                }
                            }
                        }
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            upAttachment((Part) part.getContent(), pathName, adjuncts);
        }
    }

    //保存正文并修改正文嵌图 返回值为正文  有用
    public static String moveContentPicture(MimeMessage m, List<email_adjunct> adjuncts, String pathName) throws Exception {
        MimeMessageParser parser = new MimeMessageParser(m).parse();
        String contentStr = parser.getHtmlContent();
        contentStr = parser.getHtmlContent();
        int contentStrType = 0;//正文为html文本
        if (contentStr == null) {
            contentStr = parser.getPlainContent();//正文为纯文本
            contentStrType = 1;
            if (contentStr == null) {
                contentStr = "";
            }
        }
        for (email_adjunct ad : adjuncts) {
            if (ad.getCidHas() != null) {
                if (ad.getNewHasAtta() == null) {
                    String cid = ad.getCidHas();
                    DataSource ds = parser.findAttachmentByCid(cid);//获取到附件
                    InputStream inputStream = ds.getInputStream();
                    IFtpService ftp = new ImpFtpService();
                    String upPath = ftp.uploadEmailAdjunct(pathName, getRandomFileName(), inputStream);
                    ad.setNewHasAtta(upPath);
                } else {
                    contentStr = contentStr.replace("cid:" + ad.getCidHas(), ad.getNewHasAtta());
                }
            }
        }
        return contentStr;
    }

    //附件及正文存储过程  问题：正文图片没有更换，附件没有上传成功   有用
    public static void upAdjunct(email_email email, IMAPFolder inbox, email_Pop3 pop3, EmailService emailService, IFtpService iFtpService) throws Exception {
        List<email_adjunct> adjuncts = emailService.selectAdjunctForEmail_ID(email.getEmail_id());

        MimeMessage message = (MimeMessage) inbox.getMessageByUID(email.getMessage_id());//
        //保存附件
        String pathName = "/email/" + pop3.getEmail_adress() + "/" + email.getMessage_id() + "/";
        upAdjunct(message, pathName, adjuncts);
        //修改正文
        String context = moveContentPicture(message, adjuncts, pathName);
        //保存正文至数据库
        email_adjunct adtext = new email_adjunct();
        adtext.setIsText(1);
        adtext.setEmail_id(email.getEmail_id());
        adtext.setTextAddress(context);
        adtext.setStatue(1);
        emailService.insertEmail_adjunct(adtext);
        //修改数据库adjunct表及email表
        emailService.updateEmail_emailReady1(email.getEmail_id());
        for (email_adjunct ad : adjuncts) {
            emailService.updateUpAdjunct(ad);
        }
    }

    //规则和邮件进行比对，符合返回true 不符合返回flase
    public static boolean compareEmail(email_email email, searchEmail search, EmailService emailService) {
        //审批人和审批日期尚未完善
        boolean com = false;
        //判断主题；like
        if (search.getSub() == 1) {//主题模糊匹配
            if (search.getSubject() != null && email.getSubject() != null) {
                com = email.getSubject().contains(search.getSubject());
                if (com == false) {
                    return com;
                }
            }
        } else {
            if (search.getSubject() != null && email.getSubject() != null) {
                com = search.getSubject().equals(email.getSubject());
                if (com == false) {
                    return com;
                }
            }
        }//主题模糊匹配

        //判断标签
        if (search.getTag() != null && email.getTag() != null) {
            com = email.getTag().contains(search.getTag());
            if (com == false) {
                return com;
            }
        }
        //判断收件人
        if (search.getRecipientName() != null && email.getRecipientName() != null) {
            com = search.getRecipientName().equals(email.getRecipientName());
            if (com == false) {
                return com;
            }
        }
        //判断收件地址
        if (search.getRecipientAddress() != null && email.getRecipientAddress() != null) {
            com = search.getRecipientAddress().equals(email.getRecipientAddress());
            if (com == false) {
                return com;
            }
        }
        //收件时间
        if (search.getRecDateStart() != null && search.getRecDateEnd() != null && email.getRecDate() != null) {
            Date start = null;
            Date end = null;
            Date recDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                //使用SimpleDateFormat的parse()方法生成Date
                start = sdf.parse(search.getRecDateStart());
                end = sdf.parse(search.getRecDateEnd());
                recDate = sdf.parse(email.getRecDate());
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
            //recDate比后者大就返回1，小就返回-1
            int i = recDate.compareTo(start);
            int i1 = recDate.compareTo(end);
            if (i == -1) {
                return false;
            }
            if (i1 == 1) {
                return false;
            }
        }
        //发件人
        if (search.getAddresser() != null && email.getAddresser() != null) {
            com = search.getAddresser().equals(email.getAddresser());
            if (com == false) {
                return com;
            }
        }
        //发件地址
        if (search.getSenderAddresser() != null && email.getSenderAddresser() != null) {
            String senderAddresser = search.getSenderAddresser();
            String[] split = senderAddresser.split(";");
            com=false;
            for(int i=0;i<split.length;i++){
                if(split[i].equals(email.getSenderAddresser())){
                    com=true;
                }
            }
            if (com == false) {
                return com;
            }
        }
        //发件时间sendDateStart   sendDateEnd
        if (search.getSendDateStart() != null && search.getSendDateEnd() != null && email.getSendDate() != null) {
            Date start = null;
            Date end = null;
            Date sendDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                //使用SimpleDateFormat的parse()方法生成Date
                start = sdf.parse(search.getSendDateStart());
                end = sdf.parse(search.getSendDateEnd());
                sendDate = sdf.parse(email.getSendDate());
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
            //recDate比后者大就返回1，小就返回-1
            int i = sendDate.compareTo(start);
            int i1 = sendDate.compareTo(end);
            if (i == -1) {
                return false;
            }
            if (i1 == 1) {
                return false;
            }
        }
        //抄送人
        if (search.getCopyer() != null && email.getCopyer() != null) {
            com = search.getCopyer().equals(email.getCopyer());
            if (com == false) {
                return com;
            }
        }
        //抄送地址
        if (search.getCopyAddress() != null && email.getCopyAddress() != null) {
            com = search.getCopyAddress().equals(email.getCopyAddress());
            if (com == false) {
                return com;
            }
        }

        //搜索没有附件的邮件和有附件的邮件  当搜索没有附件的邮件的时候，邮件包含附件为false;当搜索有附件的邮件时，邮件没有附件返回false
        //email.getAdjunctNum()！=0代表得是email是有附件的
        //search.getIsAdjunct() 0是不包含附件，1是包含附件  -1是不限
        if (search.getIsAdjunct() == 0 && email.getAdjunctNum() !=0) {//搜索不包含附件，邮件包含附件，无效
            return false;
        }
        if (search.getIsAdjunct() ==1 && email.getAdjunctNum() == 0) {//搜索条件包含附件，邮件不含附件
            return false;
        }
        int adj = -1;//附件名是否相同控制器-1为没有该选项，0为不同，1为相同
        if (search.getIsAdjunct() !=0 && email.getAdjunctNum() != 0) {//搜索条件可能含有附件，邮件含有附件的情况下
            if (search.getAdjunct() != null) {
                adj = 0;
                List<email_adjunct> email_adjuncts = emailService.selectAdjunctForEmail_ID(email.getEmail_id());
                for (email_adjunct ad : email_adjuncts) {
                    if (ad.getAdjunctName().equals(search.getAdjunct())) {
                        adj = 1;
                    }
                }
            }
        }
        if (adj == 0) {
            com = false;
        }
        return com;
    }

    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }

    //根据提供的pop获取到最新的三位uuid集合
    public static List<String> getTreeUUid(email_Pop3 pop) {
        String pop_email_num1 = pop.getPop_email_num();
        List<String> uuids = new ArrayList<>();
        boolean equals = pop_email_num1.equals("-1");
        if (equals == false) {
            String[] split = pop_email_num1.split(",");
            for (String s : split) {
                uuids.add(s);
            }
        }
        return uuids;
    }

    // String（0单发、1群发、2接收，3草稿，4待发，5已发，6垃圾，7回收)
    ///控制草稿 待发  群发 已发  垃圾  回收
    //邮件类型控制
    public static int emailClassForPage(String leftPage) {
        int i = -1;
        if (leftPage.equals("草稿")) {
            i = 3;
        } else if (leftPage.equals("待发")) {
            i = 4;
        } else if (leftPage.equals("群发")) {
            i = 1;
        } else if (leftPage.equals("已发")) {
            i = 5;
        } else if (leftPage.equals("垃圾")) {
            i = 6;
        } else if (leftPage.equals("回收")) {
            i = 7;
        }else if (leftPage.equals("收件")) {
            i = 2;
        }else if (leftPage.equals("未读")) {
            i = 9;
        }else if (leftPage.equals("归并")) {
            i = 8;
        }else if (leftPage.equals("系统已发")) {
            i = 10;
        }

        return i;
    }

    //生成order类
    public static emailOrder getemailOrder(emailOrder order, String leftPage) {
        int star = -1;
        if (leftPage != null && leftPage.equals("星标")) {
            star = 1;
        }
        if (star != -1) {
            order.setXinbiao(star);
        }
        int emailClassForPage = -1;
        if (leftPage != null && leftPage.equals("星标") == false) {
            emailClassForPage = EmailUnit.emailClassForPage(leftPage);
        }
        if (emailClassForPage != -1) {
            order.setEmailClass(emailClassForPage);
        }
        return order;
    }

    //新建search
    public static searchEmail getSearch(String pop3s, String subject, String tag, String recipientName,
                                        String recipientAddress, String recDate, String addresser,
                                        String senderAddresser, String sendDate, String isAdjunct,
                                        String adjunct, String sub) {
        searchEmail search = new searchEmail();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (recDate.equals("") == false && recDate.equals(" - ") == false) {
            String[] split = recDate.split(" - ");
            search.setRecDateStart(split[0]);
            search.setRecDateEnd(split[1]);
        } else {
            search.setRecDateStart(null);
            search.setRecDateEnd(null);
        }
        if (sendDate.equals("") == false && sendDate.equals(" - ") == false) {
            String[] split = sendDate.split(" - ");
            search.setSendDateStart(split[0]);
            search.setSendDateEnd(split[1]);
        } else {
            search.setSendDateStart(null);
            search.setSendDateEnd(null);
        }
        if (subject.equals("") == false) {
            search.setSubject(subject);
        }
        if (tag.equals("") == false) {
            search.setTag(tag);
        }
        if (recipientName.equals("") == false) {
            search.setRecipientName(recipientName);
        }
        if (recipientAddress.equals("") == false) {
            search.setRecipientAddress(recipientAddress);
        }
        if (addresser.equals("") == false) {
            search.setAddresser(addresser);
        }
        if (senderAddresser.equals("") == false) {
            search.setSenderAddresser(senderAddresser);
        }
        if (isAdjunct != null) {
            if (isAdjunct.equals("含附件")) {
                search.setIsAdjunct(1);
            }
            if (isAdjunct.equals("不含附件")) {
                search.setIsAdjunct(0);
            }
            if (isAdjunct.equals("不限")) {
                search.setIsAdjunct(-1);
            }
        }
        if (adjunct.equals("") == false) {
            search.setAdjunct(adjunct);
        }
        List<Integer> pop3IDS = new ArrayList<>();
        if (pop3s.equals("") == false) {
            String[] split = pop3s.split(";");
            for (int i = 0; i < split.length; i++) {
                if (split[i] != "") {
                    pop3IDS.add(Integer.parseInt(split[i]));
                }
            }
        }
        search.setPopids(pop3IDS);
        if (sub.equals("精准")) {
            search.setSub(0);
        } else {
            search.setSub(1);
        }

        return search;
    }

    //获取到所有的img链接
    public static List<String> getMatchString(String content) {
        List<String> pics = new ArrayList<>(); // 因文件可能有多张图片，故用集合来存储结果
        Pattern compile = Pattern.compile("<img.*?>"); // "<img.*?>" : 获取标签的正则
        Matcher matcher = compile.matcher(content); // string：后台返的内容，图片就是从中提取的
        while (matcher.find()) {
            String img = matcher.group();
            Matcher m = Pattern.compile("\"http?(.*?)(\"|>|\\s+)").matcher(img);
            m.find();
            String url = m.group();
            pics.add(url.substring(1, url.length() - 1));
        }
        for (String ur : pics) {
            System.out.println(ur);
        }
        return pics;
    }

    //递归删除空文件夹
    public static void clear(File dir) {
        File[] dirs = dir.listFiles();
        for (int i = 0; i < dirs.length; i++) {
            if (dirs[i].isDirectory()) {
                clear(dirs[i]);
            }else{
                dirs[i].delete();
            }
        }
        if (dir.isDirectory() && dir.delete()){
            System.out.println("清理成功" );
        };
    }

    //生成cid
    public static  String getCid(){
        Random rm=new Random();
        String cid="";
        for(int i=0;i<10;i++){
            cid+=rm.nextInt(10);
        }
        return cid;
    }

    //根据邮箱账号识别常用的服务器地址和端口号
    public void judgeEmail_Server(String serv){
        email_Server server=new email_Server();
        if(serv.endsWith("163.com")){

        }else if(serv.endsWith("126.com")){

        }else if(serv.endsWith("qq.com")){

        }else if(serv.endsWith("qq.com")){

        }else if(serv.endsWith("qq.com")){

        }else if(serv.endsWith("qq.com")){

        }else if(serv.endsWith("qq.com")){

        }else if(serv.endsWith("qq.com")){

        }else if(serv.endsWith("qq.com")){

        }
    }

    public static String getWeb(HttpServletRequest request){
        String basePath = request.getScheme()+"://"
                +request.getServerName()+":" +request.getServerPort()+ request.getContextPath()   +"/";
        return basePath;
    }

    private static OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    //判断磁盘使用率
    public static double diskLoad(){
        File diskPartition = new File("C:");
        long totalCapacity = diskPartition.getTotalSpace()/ (1024 * 1024 * 1024);
        long freePartitionSpace = diskPartition.getFreeSpace()/ (1024 * 1024 * 1024);
        return (freePartitionSpace*1.0/totalCapacity)*100;
    }
    //判断cpu使用率
    public static int cpuLoad() {
        double cpuLoad = osmxb.getSystemCpuLoad();
        int percentCpuLoad = (int) (cpuLoad * 100);
        return percentCpuLoad;
    }
    //判断内存使用率
    public static int memoryLoad() {
        double totalvirtualMemory = osmxb.getTotalPhysicalMemorySize();
        double freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
        double value = freePhysicalMemorySize/totalvirtualMemory;
        int percentMemoryLoad = (int) ((1-value)*100);
        return percentMemoryLoad;

    }
    //将Java对象序列化为byte[]
    public static byte[] obj2byte(Object obj) throws Exception {
        byte[] ret = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(obj);
        out.close();
        ret = baos.toByteArray();
        baos.close();
        return ret;
    }
    //将byte[]反序列化为Java对象
    public static Object byte2obj(byte[] bytes) throws Exception {
        Object ret = null;
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(bais);
        ret = in.readObject();
        in.close();
        return ret;
    }

    //将png转换成jpg格式
    public static InputStream getJpg(MultipartFile file, String tem,String fileName){
        BufferedImage bufferedImage;
        String fen = System.getProperty("file.separator");
        InputStream inputStream=null;
        try {
            //read image file
            bufferedImage = ImageIO.read(file.getInputStream());
            // create a blank, RGB, same width and height, and a white background
            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
                    bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
            //TYPE_INT_RGB:创建一个RBG图像，24位深度，成功将32位图转化成24位
            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
            // write to jpeg file
            File file1 = new File(tem + fen + fileName);
            ImageIO.write(newBufferedImage, "jpg", file1);
            inputStream=new FileInputStream(file1);
         } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }
    //复制文件
    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }
}
